#include "sphere.h"

namespace rt
{

Sphere::Sphere()
{
    centre = Point();
    rayon = 1;
}

Sphere::Sphere(Point p, double r)
{
    centre =p ;
    rayon =r;
}

Intersection Sphere::intersect(Ray r)
{
    Intersection inter= Intersection();
    Vector fullRay = Vector(r.getOrigin(),this->centre);
    double distance = r.getDirection()*fullRay;

    double t1,t2,intersectionIn2,d2;

    if(distance<0) return inter;

    intersectionIn2 = fullRay.norm2() - distance*distance;

    if(intersectionIn2 > this->rayon) return inter;

    d2 = this->rayon*this->rayon - intersectionIn2;

    t1= distance - sqrt(d2);
    t2= distance + sqrt(d2);

    if(t1<t2) t1 = t2;
    if(t1<0.01) return inter;

    inter.setAll(r.getOrigin().data(0)+t1*r.getDirection().data(0),
                 r.getOrigin().data(1)+t1*r.getDirection().data(1),
                 r.getOrigin().data(2)+t1*r.getDirection().data(2));

    inter.setValid(true);
    return inter;
}

}
